package cn.frontop.funswitch.service.impl;

import cn.frontop.funswitch.common.CommonConstant;
import cn.frontop.funswitch.common.Result;
import cn.frontop.funswitch.dao.StaticDataDao;
import cn.frontop.funswitch.entity.StaticDataEntity;
import cn.frontop.funswitch.service.StaticDataService;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author Yun
 */
@Service("staticDataService")
public class StaticDataServiceImpl extends ServiceImpl<StaticDataDao, StaticDataEntity> implements StaticDataService {


    @Override
    public Result<String> warehousing(MultipartFile file, Integer projectId, String... sheets) {
        //清空所有相关数据
        this.remove(new QueryWrapper<StaticDataEntity>().lambda().eq(StaticDataEntity::getProjectId, projectId));
        //临时保存
        File temp = new File(CommonConstant.TEMPORARY_DIRECTORY + CommonConstant.FILE_NAME);
        ArrayList<StaticDataEntity> savedList = new ArrayList<>();
        try {
            file.transferTo(temp);
            for (int i = 0; i < sheets.length; i++) {
                try (ExcelReader reader = ExcelUtil.getReader(temp, i)) {
                    List<Map<String, Object>> maps = reader.readAll();
                    int finalI = i;
                    //遍历转换成实体对象
                    savedList.addAll(maps.stream().map(t -> {
                        StaticDataEntity staticDataEntity = new StaticDataEntity();
                        staticDataEntity.setName(String.valueOf(t.get("name")));
                        staticDataEntity.setValue(String.valueOf(t.get("value")));
                        staticDataEntity.setProjectId(projectId);
                        staticDataEntity.setSeat(sheets[finalI]);
                        staticDataEntity.setCreatedTime(new Date());
                        staticDataEntity.setUpdatedTime(new Date());
                        return staticDataEntity;
                    }).filter(t -> t.getName() != null && !CommonConstant.NULL.equalsIgnoreCase(t.getName().trim())).collect(Collectors.toList()));
                }
            }
            this.saveBatch(savedList);
        } catch (IOException ignored) {
        }
        return Result.ok();
    }
}